import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '@/components/Home.vue'
import Storage from '@/utils/storage'
import { getPermissionList } from '@/api'

const routes = [
  {
    name: 'home',
    path: '/',
    meta: {
      title: '首页',
    },
    redirect: 'welcome',
    component: Home,
    children: [
      {
        path: 'welcome',
        meta: {
          title: '欢迎页面',
        },
        component: () => import('@/views/Welcome.vue'),
      },
      {
        path: '/system/menu',
        meta: {
          title: '菜单管理',
        },
        component: () => import('@/views/Menu/Index.vue'),
      },
      {
        path: '/system/dept',
        meta: {
          title: '部门管理',
        },
        component: () => import('@/views/Dept/index.vue'),
      },
      {
        path: '/system/user',
        meta: {
          title: '用户管理',
        },
        component: () => import('@/views/User.vue'),
      },
      {
        path: '/system/role',
        meta: {
          title: '角色管理',
        },
        component: () => import('@/views/Role/index.vue'),
      },
      {
        path: '/audit/leave',
        meta: {
          title: '休假申请',
        },
        component: () => import('@/views/Leave/index.vue'),
      },
      {
        path: '/audit/approve',
        meta: {
          title: '待我审批',
        },
        component: () => import('@/views/Approve/index.vue'),
      },
    ]
  },
  {
    name: '404',
    meta: {
      title: '页面丢失'
    },
    path: '/404',
    component: () => import('@/views/404.vue'),
  },
  {
    name: 'login',
    path: '/login',
    meta: {
      title: '登陆'
    },
    component: () => import('@/views/Login.vue'),
  }
]

const router = createRouter({
  routes,
  history: createWebHashHistory()
})

const genRoute = (menuList) => {
  let routes = []
  const deepList = (list) => {
    while(list.length) {
      let item = list.pop();
      if (item.action) {
        routes.push({
          name: item.menuName,
          path: item.path,
          meta: {
            title: item.menuName
          },
          component: item.component,
        })
      }
      if(item.children && !item.action) {
        deepList(item.children);
      }
    }
  }
  deepList(menuList);
  return routes;
}

const checkPermission = (toPath) => {
  const hasPermission = router.getRoutes().filter(route => route.path === toPath).length
  if (hasPermission) {
    return true
  } else {
    return false
  }
}

router.beforeEach((to, from, next) => {
  if (checkPermission(to.path)) {
    document.title = to.meta.title;
    next()
  } else {
    next('/404')
  }
})

window.router = router

export default router;
